import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useAppStore } from '@/stores/appStore';
import { 
  Trophy, 
  Download, 
  Share2, 
  RotateCcw, 
  Star,
  Medal,
  Award,
  Sparkles,
  Eye,
  Shield,
  Lock
} from 'lucide-react';
import { OriginalDataDisplay } from '@/components/ui/OriginalDataDisplay';

interface Achievement {
  id: string;
  title: string;
  description: string;
  icon: React.ReactNode;
  earned: boolean;
}

interface StatCard {
  title: string;
  value: string;
  icon: React.ReactNode;
  color: string;
  description: string;
}

export function Stage6Results() {
  const { 
    zkProofData, 
    blockchainTx, 
    experienceMode,
    completeStage,
    reset 
  } = useAppStore();
  
  const [showCelebration, setShowCelebration] = useState(false);
  const [achievementsUnlocked, setAchievementsUnlocked] = useState(0);
  const [certificateGenerated, setCertificateGenerated] = useState(false);
  
  const achievements: Achievement[] = [
    {
      id: 'secret_keeper',
      title: '🔐 秘密守护者',
      description: '成功保护隐私数据不被泄露',
      icon: <Lock className="w-6 h-6" />,
      earned: true
    },
    {
      id: 'proof_master',
      title: '⚡ 证明大师',
      description: '生成有效的零知识证明',
      icon: <Sparkles className="w-6 h-6" />,
      earned: true
    },
    {
      id: 'blockchain_explorer',
      title: '🚀 区块链探索者',
      description: '成功与区块链网络交互',
      icon: <Trophy className="w-6 h-6" />,
      earned: !!blockchainTx
    },
    {
      id: 'zk_pioneer',
      title: '🌟 零知识先锋',
      description: '完成完整的零知识证明流程',
      icon: <Award className="w-6 h-6" />,
      earned: true
    }
  ];
  
  const stats: StatCard[] = [
    {
      title: '隐私保护',
      value: '100%',
      icon: <Eye className="w-8 h-8" />,
      color: 'text-crypto-green',
      description: '您的秘密888888从未暴露'
    },
    {
      title: '数学完整性',
      value: '100%',
      icon: <Shield className="w-8 h-8" />,
      color: 'text-quantum-blue',
      description: 'PLONK证明数学验证通过'
    },
    {
      title: '零知识性',
      value: '100%',
      icon: <Lock className="w-8 h-8" />,
      color: 'text-proof-purple',
      description: '验证过程零信息泄露'
    },
    {
      title: '验证成功率',
      value: '100%',
      icon: <Star className="w-8 h-8" />,
      color: 'text-yellow-400',
      description: '智能合约验证通过'
    }
  ];
  
  useEffect(() => {
    // Mark stage as completed
    completeStage('results');
    
    // Start celebration sequence
    const timer = setTimeout(() => {
      setShowCelebration(true);
      
      // Unlock achievements one by one
      achievements.forEach((achievement, index) => {
        if (achievement.earned) {
          setTimeout(() => {
            setAchievementsUnlocked(prev => prev + 1);
          }, (index + 1) * 800);
        }
      });
      
      // Generate certificate
      setTimeout(() => {
        setCertificateGenerated(true);
      }, achievements.length * 800 + 1000);
    }, 1000);
    
    return () => clearTimeout(timer);
  }, [completeStage]);
  
  const handleDownloadCertificate = () => {
    // Create a simple certificate data
    const certificateData = {
      title: '零知识证明大师证书',
      recipient: '演示用户',
      achievement: '成功完成零知识证明全流程演示',
      date: new Date().toLocaleDateString(),
      secretData: zkProofData?.input?.preImage,
      proofHash: blockchainTx?.txHash?.slice(0, 16) + '...',
      timestamp: Date.now()
    };
    
    const dataStr = JSON.stringify(certificateData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = 'zk-proof-certificate.json';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };
  
  const handleShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: '🎉 我完成了零知识证明演示！',
          text: '刚刚完成了一个神奇的零知识证明演示，在不透露秘密的情况下证明了我的知识！',
          url: window.location.href
        });
      } catch (error) {
        console.log('分享失败:', error);
      }
    } else {
      // Fallback: copy to clipboard
      const text = '🎉 我完成了零知识证明演示！刚刚体验了在不透露秘密的情况下证明知识的神奇过程！';
      navigator.clipboard.writeText(text);
      alert('分享内容已复制到剪贴板！');
    }
  };
  
  const handleRestart = () => {
    reset();
  };
  
  return (
    <div className="stage-container relative">
      {/* Celebration fireworks background */}
      {showCelebration && (
        <div className="fixed inset-0 pointer-events-none z-0">
          {Array.from({ length: 20 }, (_, i) => (
            <motion.div
              key={i}
              className="absolute w-4 h-4 rounded-full"
              style={{
                background: ['#3b82f6', '#10b981', '#8b5cf6', '#f59e0b'][i % 4],
                left: `${Math.random() * 100}%`,
                top: `${Math.random() * 100}%`,
              }}
              animate={{
                scale: [0, 1, 0],
                opacity: [0, 1, 0],
                rotate: [0, 360],
              }}
              transition={{
                duration: 2,
                delay: Math.random() * 3,
                repeat: Infinity,
                repeatDelay: Math.random() * 5 + 2,
              }}
            />
          ))}
        </div>
      )}
      
      <div className="max-w-6xl mx-auto relative z-10 w-full">
        {/* Main title */}
        <motion.div
          initial={{ opacity: 0, y: -50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="text-center mb-12"
        >
          <motion.h1
            className="text-6xl font-bold gradient-text mb-6"
            animate={showCelebration ? {
              scale: [1, 1.1, 1],
              textShadow: [
                '0 0 20px rgba(59, 130, 246, 0.5)',
                '0 0 40px rgba(16, 185, 129, 0.7)',
                '0 0 20px rgba(139, 92, 246, 0.5)'
              ]
            } : {}}
            transition={{ duration: 2, repeat: showCelebration ? Infinity : 0 }}
          >
            🎉 零知识的胜利！
          </motion.h1>
          
          <motion.p
            className="text-2xl text-gray-300"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.5 }}
          >
            恭喜您完成了零知识证明的神奇之旅
          </motion.p>
        </motion.div>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Left side - Statistics and achievements */}
          <motion.div
            initial={{ opacity: 0, x: -100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Statistics cards */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6 flex items-center">
                <Trophy className="mr-3 text-yellow-400" size={28} />
                完美表现
              </h3>
              
              <div className="grid grid-cols-2 gap-4">
                {stats.map((stat, index) => (
                  <motion.div
                    key={stat.title}
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: 0.6 + index * 0.2 }}
                    className="bg-slate-800 rounded-lg p-4 text-center"
                  >
                    <div className={`${stat.color} mb-2`}>
                      {stat.icon}
                    </div>
                    <div className={`text-2xl font-bold mb-1 ${stat.color}`}>
                      {stat.value}
                    </div>
                    <div className="text-sm font-semibold text-white mb-1">
                      {stat.title}
                    </div>
                    <div className="text-xs text-gray-400">
                      {stat.description}
                    </div>
                  </motion.div>
                ))}
              </div>
            </div>
            
            {/* Achievements */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6 flex items-center">
                <Medal className="mr-3 text-yellow-400" size={28} />
                解锁成就 ({achievementsUnlocked}/{achievements.filter(a => a.earned).length})
              </h3>
              
              <div className="space-y-3">
                {achievements.map((achievement, index) => (
                  <motion.div
                    key={achievement.id}
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ 
                      opacity: index < achievementsUnlocked ? 1 : 0.3,
                      x: 0,
                      scale: index === achievementsUnlocked - 1 ? [1, 1.05, 1] : 1
                    }}
                    transition={{ 
                      delay: index * 0.8,
                      scale: { duration: 0.5, repeat: index === achievementsUnlocked - 1 ? 3 : 0 }
                    }}
                    className={`p-4 rounded-lg border transition-all ${
                      achievement.earned && index < achievementsUnlocked
                        ? 'border-yellow-400 bg-yellow-400/10'
                        : 'border-gray-600 bg-gray-700/50'
                    }`}
                  >
                    <div className="flex items-center space-x-3">
                      <div className={`${
                        achievement.earned && index < achievementsUnlocked 
                          ? 'text-yellow-400' 
                          : 'text-gray-400'
                      }`}>
                        {achievement.icon}
                      </div>
                      
                      <div className="flex-1">
                        <h4 className={`font-semibold ${
                          achievement.earned && index < achievementsUnlocked 
                            ? 'text-yellow-400' 
                            : 'text-gray-400'
                        }`}>
                          {achievement.title}
                        </h4>
                        <p className="text-gray-300 text-sm">
                          {achievement.description}
                        </p>
                      </div>
                      
                      {achievement.earned && index < achievementsUnlocked && (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          transition={{ delay: index * 0.8 + 0.5, type: "spring" }}
                        >
                          <Star className="w-6 h-6 text-yellow-400 fill-current" />
                        </motion.div>
                      )}
                    </div>
                  </motion.div>
                ))}
              </div>
            </div>
          </motion.div>
          
          {/* Right side - Summary and actions */}
          <motion.div
            initial={{ opacity: 0, x: 100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.6, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Journey summary */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6">🗺️ 您的神奇之旅</h3>
              
              <div className="space-y-4">
                <div className="flex items-center space-x-3 p-3 bg-slate-800 rounded-lg">
                  <div className="w-8 h-8 bg-quantum-blue rounded-full flex items-center justify-center text-white font-bold text-sm">
                    1
                  </div>
                  <div>
                    <div className="font-semibold text-white">输入秘密</div>
                    <div className="text-sm text-gray-400">
                      将秘密 {zkProofData?.input?.preImage} 存储到量子保险箱
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center space-x-3 p-3 bg-slate-800 rounded-lg">
                  <div className="w-8 h-8 bg-crypto-green rounded-full flex items-center justify-center text-white font-bold text-sm">
                    2
                  </div>
                  <div>
                    <div className="font-semibold text-white">生成证明</div>
                    <div className="text-sm text-gray-400">
                      使用PLONK算法创建零知识证明
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center space-x-3 p-3 bg-slate-800 rounded-lg">
                  <div className="w-8 h-8 bg-proof-purple rounded-full flex items-center justify-center text-white font-bold text-sm">
                    3
                  </div>
                  <div>
                    <div className="font-semibold text-white">区块链验证</div>
                    <div className="text-sm text-gray-400">
                      通过智能合约验证证明有效性
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center space-x-3 p-3 bg-slate-800 rounded-lg">
                  <div className="w-8 h-8 bg-yellow-400 rounded-full flex items-center justify-center text-black font-bold text-sm">
                    ✓
                  </div>
                  <div>
                    <div className="font-semibold text-white">成功完成</div>
                    <div className="text-sm text-gray-400">
                      隐私得到完美保护，知识得到有效证明
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            {/* Certificate */}
            {certificateGenerated && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="floating-card border-yellow-400 bg-yellow-400/5"
              >
                <h3 className="text-2xl font-semibold text-yellow-400 mb-4 flex items-center">
                  <Award className="mr-3" size={28} />
                  🏆 专属证书
                </h3>
                
                <div className="bg-gradient-to-br from-yellow-400/10 to-orange-400/10 rounded-lg p-6 border border-yellow-400/30">
                  <div className="text-center">
                    <div className="text-4xl mb-4">🎖️</div>
                    <h4 className="text-xl font-bold text-white mb-2">
                      零知识证明大师证书
                    </h4>
                    <p className="text-gray-300 text-sm mb-4">
                      特此证明您已成功掌握零知识证明技术，<br />
                      能够在保护隐私的同时有效证明知识。
                    </p>
                    <div className="text-xs text-gray-400">
                      颁发日期：{new Date().toLocaleDateString()}<br />
                      证书编号：{blockchainTx?.txHash?.slice(0, 16)}...
                    </div>
                  </div>
                </div>
                
                <button
                  onClick={handleDownloadCertificate}
                  className="w-full mt-4 bg-yellow-400 hover:bg-yellow-500 text-black font-semibold py-3 px-6 rounded-lg transition-colors flex items-center justify-center"
                >
                  <Download className="w-5 h-5 mr-2" />
                  下载证书
                </button>
              </motion.div>
            )}
            
            {/* Actions */}
            <div className="floating-card">
              <h3 className="text-lg font-semibold text-white mb-4">🎯 下一步行动</h3>
              
              <div className="space-y-3">
                <button
                  onClick={handleShare}
                  className="w-full bg-quantum-blue hover:bg-blue-600 text-white font-semibold py-3 px-6 rounded-lg transition-colors flex items-center justify-center"
                >
                  <Share2 className="w-5 h-5 mr-2" />
                  分享您的成就
                </button>
                
                <button
                  onClick={handleRestart}
                  className="w-full bg-gray-700 hover:bg-gray-600 text-white font-semibold py-3 px-6 rounded-lg transition-colors flex items-center justify-center"
                >
                  <RotateCcw className="w-5 h-5 mr-2" />
                  重新体验
                </button>
              </div>
            </div>
            
            {/* Learning resources */}
            {experienceMode.showTechDetails && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 1 }}
                className="bg-slate-800/50 rounded-lg p-4 border border-slate-700"
              >
                <h4 className="text-lg font-semibold text-white mb-3">📚 深入学习</h4>
                <div className="space-y-2 text-sm text-gray-300">
                  <p>• 探索更多零知识证明应用场景</p>
                  <p>• 学习其他zk-SNARK协议（Groth16、STARK等）</p>
                  <p>• 了解隐私计算和区块链隐私保护技术</p>
                  <p>• 参与开源零知识证明项目开发</p>
                </div>
              </motion.div>
            )}
          </motion.div>
        </div>
        
        {/* Final message */}
        <motion.div
          initial={{ opacity: 0, y: 50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 2 }}
          className="text-center mt-12"
        >
          <div className="floating-card max-w-2xl mx-auto">
            <h3 className="text-2xl font-bold gradient-text mb-4">
              🌟 零知识证明的力量
            </h3>
            <p className="text-gray-300 leading-relaxed">
              您刚刚体验了密码学史上最重要的突破之一。零知识证明技术正在重塑数字世界的隐私保护，
              从区块链到人工智能，从身份验证到数据分析，这项技术将为构建更安全、更私密的数字未来提供坚实基础。
            </p>
            
            <motion.div
              className="mt-6 text-quantum-blue"
              animate={{ 
                opacity: [0.7, 1, 0.7],
                scale: [1, 1.02, 1]
              }}
              transition={{ duration: 3, repeat: Infinity }}
            >
              <Sparkles className="w-8 h-8 mx-auto mb-2" />
              <p className="font-semibold">感谢您的参与，隐私计算的未来因您而精彩！</p>
            </motion.div>
          </div>
        </motion.div>
        
        {/* Original Data Display */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 2.5 }}
          className="mt-8"
        >
          <OriginalDataDisplay 
            title="完整验证的原始数据"
            compact={experienceMode.id === 'quick' || experienceMode.id === 'presentation'}
            showControls={experienceMode.showTechDetails || experienceMode.showCode}
            className="max-w-2xl mx-auto"
          />
        </motion.div>
      </div>
    </div>
  );
}